package com.zbkj.service.service.publics.attachment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.model.system.SystemAttachment;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.SystemAttachmentMoveRequest;
import com.zbkj.common.request.SystemAttachmentRequest;
import com.zbkj.common.request.SystemAttachmentSearchRequest;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.common.utils.UploadUtil;
import com.zbkj.common.vo.FileResultVo;
import com.zbkj.service.dao.SystemAttachmentDao;
import com.zbkj.service.service.ai.utils.Base64ToMultipartFile;
import com.zbkj.service.service.config.SystemConfigService;
import com.zbkj.service.thirdparty.files.enums.UploadDirectoryEnum;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件管理表-service接口-实现类
 * @author lijie
 */
@Log4j2
@Service
public class SystemAttachmentServiceImpl extends ServiceImpl<SystemAttachmentDao, SystemAttachment>
        implements SystemAttachmentService {

    @Resource
    private SystemAttachmentDao dao;

    @Autowired
    private SystemConfigService systemConfigService;
    /**
     * 保存文件
     * @param file FileResultVo 文件信息
     * @param pid Integer
     * @author Mr.Zhang
     * @since 2020-05-08
     */
    @Override
    public void create(FileResultVo file, Integer pid) {
        SystemAttachment systemAttachment = new SystemAttachment();
        systemAttachment.setName(file.getFileName());
        systemAttachment.setAttDir(file.getUrl());
        systemAttachment.setSattDir(file.getUrl());
        systemAttachment.setAttSize(file.getFileSize().toString());
        systemAttachment.setAttType(file.getType());
        systemAttachment.setImageType(1);   //图片上传类型 1本地 2七牛云 3OSS 4COS, 默认本地，任务轮询数据库放入云服务
        systemAttachment.setAttDir(file.getServerPath()); // 服务器上存储的绝对地址， 上传到云的时候使用
        systemAttachment.setPid(pid);
        save(systemAttachment);
    }


    /**
     * 同步到云服务， 更新图片上传类型
     * @param attId Integer 主键id
     * @param type int 图片上传类型 1本地 2七牛云 3OSS 4COS
     */
    @Override
    public void updateCloudType(Integer attId, int type) {
        SystemAttachment systemAttachment = new SystemAttachment();
        systemAttachment.setAttId(attId);
        systemAttachment.setImageType(type);
        updateById(systemAttachment);
    }

    /**
     * 附件分页
     * @param pid Integer pid
     * @param pageParamRequest PageParamRequest 分页参数
     * @return List<SystemAttachment>
     */
    @Override
    public List<SystemAttachment> getList(Integer pid, String attType, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<SystemAttachment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemAttachment::getPid, pid);
        if(StringUtils.isNotEmpty(attType)){
            lambdaQueryWrapper.in(SystemAttachment::getAttType, StringUtils.split(attType,","));
        }
        lambdaQueryWrapper.orderByDesc(SystemAttachment::getAttId);
        return dao.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<SystemAttachment> getUserPageList(PageParamRequest pageParamRequest,int uid,Integer pid) {
        //开启分页
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //定义查询-附件表
        LambdaQueryWrapper<SystemAttachment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //条件-用户id
        lambdaQueryWrapper.eq(SystemAttachment::getUserId,uid);
        //条件-分类id
        lambdaQueryWrapper.eq(SystemAttachment::getPid, pid);
        //排序-attid
        lambdaQueryWrapper.orderByDesc(SystemAttachment::getAttId);
        return dao.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<SystemAttachment> getList(SystemAttachmentSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<SystemAttachment> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //条件-上级ID
        if(request.getPid() != null){
            lambdaQueryWrapper.eq(SystemAttachment::getPid, request.getPid());
        }

        //条件-多个上级ID
        if(!StringUtils.isBlank(request.getPidStr())){
            lambdaQueryWrapper.in(SystemAttachment::getPid,request.getPidStr().split(","));
        }

        //条件-关键字
        if(!StringUtils.isBlank(request.getKeywords())){
            lambdaQueryWrapper.like(SystemAttachment::getName, request.getKeywords());
            lambdaQueryWrapper.or().like(SystemAttachment::getAttId,request.getKeywords());
            lambdaQueryWrapper.or().like(SystemAttachment::getAttType,request.getKeywords());
        }

        //排序
        lambdaQueryWrapper.orderByDesc(SystemAttachment::getAttId);
        return dao.selectList(lambdaQueryWrapper);
    }

    /**
     * 给图片加前缀
     * @param path String 路径
     * @return String
     */
    @Override
    public String prefixImage(String path) {
        // 如果那些域名不需要加，则跳过
        return path.replace(Constants.UPLOAD_TYPE_IMAGE+"/", getCdnUrl() + "/"+ Constants.UPLOAD_TYPE_IMAGE+"/");
    }

    /**
     * 给文件加前缀
     * @param path String 路径
     * @return String
     */
    @Override
    public String prefixFile(String path) {
        if (path.contains("file/excel")) {
            String cdnUrl = systemConfigService.getValueByKey("local" + "UploadUrl");
            return path.replace("file/", cdnUrl + "/file/");
        }
        return path.replace("file/", getCdnUrl() + "/file/");
    }

    /**
     * 获取cdn url
     * @return String
     */
    private String getCdnUrl() {
//        return asyncService.getCurrentBaseUrl();
        String uploadType = systemConfigService.getValueByKeyException("uploadType");
        //获取配置信息
        int type = Integer.parseInt(uploadType);
        String pre = "local";
        switch (type) {
            case 2:
                pre = "qn";
                break;
            case 3:
                pre = "al";
                break;
            case 4:
                pre = "tx";
                break;
            default:
                break;
        }
        return systemConfigService.getValueByKey(pre+"UploadUrl");
    }

    /**
     * 清除 cdn url， 在保存数据的时候使用
     * @param path String 文件路径
     * @return String
     */
    @Override
    public String clearPrefix(String path) {
        if(StringUtils.isBlank(path)){
            return path;
        }
        Constants.CND_URL = getCdnUrl();
        if(path.contains(getCdnUrl() + "/")){
            return path.replace(getCdnUrl() + "/", "");
        }

        return path;
    }

    /**
     * 新增附件
     * @param systemAttachmentRequest 新增参数
     */
    @Override
    public Boolean add(SystemAttachmentRequest systemAttachmentRequest) {
        SystemAttachment systemAttachment = new SystemAttachment();
        BeanUtils.copyProperties(systemAttachmentRequest, systemAttachment);
        return save(systemAttachment);
    }

    /**
     * 编辑附件
     * @param systemAttachmentRequest 更新参数
     */
    @Override
    public Boolean edit(SystemAttachmentRequest systemAttachmentRequest) {
        SystemAttachment systemAttachment = new SystemAttachment();
        BeanUtils.copyProperties(systemAttachmentRequest, systemAttachment);
        return updateById(systemAttachment);
    }

    /**
     * 更改图片目录
     * @param move 参数
     */
    @Override
    public Boolean updateAttrId(SystemAttachmentMoveRequest move) {
        LambdaUpdateWrapper<SystemAttachment> lup = new LambdaUpdateWrapper<>();
        lup.in(SystemAttachment::getAttId, CrmebUtil.stringToArray(move.getAttrId()));
        lup.set(SystemAttachment::getPid, move.getPid());
        return update(lup);
    }

    @Override
    public List<SystemAttachment> imgUrlSaveInfo(String urls,String imgKey,Integer pid){

        //处理图片路径-并上传
        List<SystemAttachment> list = new ArrayList<>();
        String[] imgUrlArr = urls.split(",");
        for (String url: imgUrlArr) {
            SystemAttachment attachment = new SystemAttachment();
            attachment.setSattDir(url);
            attachment.setName(imgKey);
            attachment.setPid(pid);
            attachment.setAttType("png");
            attachment.setImageType(1);
            list.add(attachment);
        }
        saveBatch(list);
        //返回结果
        return list;
    }

    /**
     * base64图片保存到本地
     * @param base64Img             base64图片数据
     * @param configImagePath       配置的图片存储路径-前缀
     * @param imgName               图片名称
     * @return  本地存储路径
     * @throws IOException
     */
    @Override
    public SystemAttachment base64ImgSaveLocalhost(String base64Img,String configImagePath, String imgName) throws IOException {
        //base6转MultipartFile
        String types = MediaType.APPLICATION_OCTET_STREAM.toString();
        log.info(types);
        String base64Image = new StringBuffer()
                .append("data:").append(types).append(";base64,")
                .append(base64Img)
                .toString();
        log.info(base64Image);
        MultipartFile multipartFile = Base64ToMultipartFile.base64ToMultipart(base64Image);

        //得到本地储存路径-后缀
        String filePath = this.getLocalhostSavePathSuffix(imgName);

        //创建文件
        File file = UploadUtil.createFile(configImagePath + filePath);
        //保存文件
        multipartFile.transferTo(file);

        //返回图片信息
        SystemAttachment attachment = new SystemAttachment();
        attachment.setName(imgName);
        attachment.setSattDir(filePath);
        attachment.setAttType("png");
        attachment.setAttSize(String.valueOf(multipartFile.getSize()));
        attachment.setImageType(1);
        return attachment;
    }

    private static String getLocalhostSavePathSuffix(String imgName) {
        //设置文件路径
        //当前日期
        String thisDate = DateUtil.nowDate(Constants.DATE_FORMAT_DATE).replace("-", "/") + "/";
        String filePath = new StringBuffer()
                .append(UploadDirectoryEnum.crmebimage).append("/")
                .append(UploadDirectoryEnum.aiHairstyleMaterials).append("/")
                .append(thisDate)
                .append(imgName)
                .append(".png")
                .toString();
        log.info(thisDate);
        log.info(filePath);
        return filePath;
    }

    @Override
    public String getConfigPid(String configField) {
        return systemConfigService.getValueByKeyException(configField);
    }
}

